import React, {Component} from 'react';
import PropTypes from 'prop-types';
import LogService from "../../services/base/LogService";
import {FlatList} from "react-native";

/**
 * 列表封装
 * 支持垂直分页: 设置enableVPage true  和 itemHeight高度即可
 * 支持水平分页，pagingEnabled={true}
 * 支持当前显示的item是哪个 onVisibleItem
 *
 */
export default class MFlatList extends Component {

  static propTypes = {
    // 支持当前滑动到那个item的回调
    onVisibleItem: PropTypes.func,  // 参数  index， item

    // item的高度 垂直分页
    itemHeight: PropTypes.number,
    enableVPage: PropTypes.bool,
  }

  static defaultProps = {
    enableVPage: false,
  };

  constructor(props) {
    super(props);
    this.viewabilityConfig = {viewAreaCoveragePercentThreshold: 50};

    this.state = {isScrolling: false, y: 0};
  }

  componentWillUnmount() {
    this.timer && clearTimeout(this.timer);
  }


  _onViewableItemsChanged = (visibleRowNumbers) => {

    LogService.debug(visibleRowNumbers);

    const visiableSize = visibleRowNumbers.viewableItems.length;
    if (visiableSize > 0) {
      visibleRow = visibleRowNumbers.viewableItems[visiableSize - 1];

      this.setState({
        visibleRow:{
          index: visibleRow.index,
          item: visibleRow.item,
        }
      });

      if (!this.state.isScrolling){
        this.scrollToEnd();
      }
    }
  }

  /**
   * 开始拖动
   * @param event
   * @private
   */
  _onScrollBeginDrag = (event) => {
    this.setState({
      isScrolling: true
    });
  }

  /**
   * 停止拖动
   * @param event
   * @private
   */
  _onScrollEndDrag = (event) => {

    this.setState({
      isScrolling: false
    });

    this.timer = setTimeout(
      () => {
        if (!this.state.isScrolling) {
          this.scrollToEnd();
        }
      },
      100
    );
  }

  /**
   * 滚动动画开始
   * @param event
   * @private
   */
  _onMomentumScrollBegin = (event) => {
    this.setState({
      isScrolling: true
    });
  }

  /**
   * 滚动动画结束
   * @param event
   * @private
   */
  _onMomentumScrollEnd = (event) => {
    this.setState({
      isScrolling: false
    });
    this.scrollToEnd();
  }

  scrollToEnd = () => {

    const {y, visibleRow} = this.state;
    const {enableVPage, itemHeight} = this.props;

    !!this.props.onVisibleItem && this.props.onVisibleItem(visibleRow.index, visibleRow.item);
    LogService.debug('滚动结束', '当前item的位置:',visibleRow);

    if (!enableVPage)
      return;

    let itemNumb = parseInt(y / itemHeight);
    if (y % itemHeight > (itemHeight / 2)) {
      itemNumb += 1;
    }
    this._flatList.scrollToIndex({viewPosition: 0, index: itemNumb});
  }



  render() {
    return (

      <FlatList
        ref={(flatList) => this._flatList = flatList}
        // 获取垂直方向滚动的位置
        onScroll={(event) => {

          this.setState({
            y: event.nativeEvent.contentOffset.y,
          });
        }}

        onScrollBeginDrag={this._onScrollBeginDrag}

        onScrollEndDrag={this._onScrollEndDrag}

        onMomentumScrollBegin={this._onMomentumScrollBegin}

        onMomentumScrollEnd={this._onMomentumScrollEnd}

        // item 显示隐藏的回调
        viewabilityConfig={this.viewabilityConfig}
        onViewableItemsChanged={this._onViewableItemsChanged}

        // key
        keyExtractor={(item, index) => String(index)}

        {...this.props}
      />
    );
  }
}

